#include "stdafx.h"
#include "../Interface/FileAppender.h"
#include <iomanip>

namespace SimpleLog
{
	const char* unicode2utf8(const wchar_t* lpszUnicode)
	{
		static std::string strUTF8;
		strUTF8.clear();

		auto len = wcslen(lpszUnicode);
		auto nNeed = ::WideCharToMultiByte(CP_UTF8, 0, lpszUnicode, len, nullptr, 0, nullptr, nullptr);
		char* ch = new char[nNeed + 1];
		memset(ch, 0, nNeed + 1);
		nNeed = ::WideCharToMultiByte(CP_UTF8, 0, lpszUnicode, len, ch, nNeed, nullptr, nullptr);
		strUTF8 = ch;
		delete[]ch;
		return strUTF8.c_str();
	}

	CFileAppender::CFileAppender(const std::wstring& strFilePath)
		: m_strFilePath(strFilePath)
	{
	}

	CFileAppender::CFileAppender(const wchar_t* lpszFilePath)
		: m_strFilePath(lpszFilePath)
	{
	}

	CFileAppender::~CFileAppender()
	{

	}

	bool CFileAppender::initAppender()
	{
		m_of.open(m_strFilePath.c_str(), std::ios_base::out);
		if (m_of.bad())
			return false;

		char chTemp[64 * 4] = { 0 };

		m_of.flags(std::ios::left);
		m_of << std::setw(10) << L"level";
		m_of << std::setw(30) << L"time";
		m_of << std::setw(10) << L"ThreadID";
		m_of << L"content" << std::endl;

		return true;
	}

	bool CFileAppender::uninitAppender()
	{
		m_of.flush();
		m_of.close();
		return true;
	}

	void CFileAppender::outputLog(const wchar_t*  lpszContent, const LogLevel & logLevel, const wchar_t*  lpszTimeStamp
		, const unsigned long & uThreadID)
	{
		m_of << std::setw(10) << unicode2utf8(GetLevelName(logLevel));
		m_of << std::setw(30) << lpszTimeStamp;
		m_of << std::setw(10) << uThreadID;
		m_of << unicode2utf8(lpszContent) << std::endl;
	}
}